package com.sport.facilities.booking.system;

import java.util.List;

import android.R.drawable;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.sport.facilities.booking.system.httptask.ConfirmBookingPageTask;
import com.sport.facilities.booking.system.httptask.ConfirmBookingResultTask;
import com.sport.facilities.booking.system.httptask.OnTaskCompleted;
import com.sport.facilities.booking.system.model.Booking;
import com.sport.facilities.booking.system.model.BookingRequestModel;
import com.sport.facilities.booking.system.ui.DialogHelper;
import com.sport.facilities.booking.system.ui.YesAction;

public class ConfirmBookingActivity extends Activity {
	private static final String TAG = "ConfirmBookingActivity";
	final Context context = this;
	final ConfirmBookingActivity confirmbkActivity = this;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.confirm_booking);

	}

	@Override
	public void onResume() {
		super.onResume();
		fnLoadConfirmBookData();
	}

	protected void fnSetConfirmBooking(List<Booking> bookingList) {
		if (bookingList.size() > 0) {

			TableLayout tbl = (TableLayout) findViewById(R.id.confirm_booking_table);
			TextView[][] tvs;
			TableRow[] tbrs;
			tvs = new TextView[bookingList.size()][6];
			tbrs = new TableRow[bookingList.size() + 1];
			int count = bookingList.size();
			for (int i = 0; i < count; i++) {
				Booking bkk = (Booking) bookingList.get(i);
				tbrs[i] = new TableRow(this);
				tbrs[i].setTag(bkk.getId());

				if (i % 2 == 0) {
					tbrs[i].setBackgroundResource(R.color.color_white);
				} else {
					tbrs[i].setBackgroundResource(R.color.color_normal_grey);
				}
				tbrs[i].setBackgroundResource(drawable.list_selector_background);

				final ConfirmBookingActivity cbmActivity = this;

				tbrs[i].setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						if (v instanceof TableRow) {
							TableRow row = (TableRow) v;
							TextView cancelid = (TextView) row.getChildAt(5);
							TextView activity = (TextView) row.getChildAt(4);
							TextView date = (TextView) row.getChildAt(0);
							TextView time = (TextView) row.getChildAt(1);
							TextView centre = (TextView) row.getChildAt(2);
							// Log.d(TAG, "2. Clicked " + child.getText());
							// Log.d(TAG, "2. Clicked " + cancelid.getText());

							final BookingRequestModel bkmodel = new BookingRequestModel();
							bkmodel.setId((String) cancelid.getText());
							Log.d(TAG, "Confirm Record with Cancel ID : "
									+ bkmodel.getId() + "?");

							AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
									context);

							// set title
							alertDialogBuilder.setTitle("Confirm Booking");

							// set dialog message
							alertDialogBuilder
									.setMessage(
											"Date:      " + date.getText()
													+ "\n" + "Time:     "
													+ ((String) time.getText()).replaceAll("\n to \n", "-") + "\n"
													+ "Centre:   "
													+ centre.getText() + "\n"
													+ "Activity: "
													+ ((String) activity.getText()).replaceAll("\n", " ") + "\n")

									.setCancelable(false)
									.setPositiveButton(
											"Yes",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int id) {
													OnTaskCompleted completeAction = new OnTaskCompleted() {
														public void onTaskCompleted(
																Object resultList) {
															DialogHelper
																	.getOkAlertDialog(
																			cbmActivity,
																			"Booking Confirmed",
																			"")
																	.show();
														}

														public void onTaskFailed(
																String errMessage) {
															DialogHelper
																	.getOkAlertDialog(
																			cbmActivity,
																			"Error In Confirm Booking",
																			errMessage)
																	.show();
														}
													};

													OnTaskCompleted completeAction2 = new OnTaskCompleted() {

														public void onTaskCompleted(
																Object result) {
															// TODO
															// Auto-generated
															// method stub
															removetbr(); //remove table rows
															onResume(); //reload the data to table
															//DialogHelper.getNewAlertDialog(getBaseContext(), "", "");
															
															
														}

														public void onTaskFailed(
																String errMessage) {
															fnfailtoconfirm();
														}

													};

													ConfirmBookingResultTask cbpTask = new ConfirmBookingResultTask(
															context,
															completeAction2);
													cbpTask.fnConfirmBook(bkmodel);
													
													
												}
											})
									.setNegativeButton(
											"No",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int id) {
													// if this button is
													// clicked, just close
													// the dialog box and do
													// nothing
													dialog.cancel();
												}
											});
							// create alert dialog
							AlertDialog alertDialog = alertDialogBuilder
									.create();
							// show it
							alertDialog.show();

						}

					}
				});
				tvs[i][1] = new TextView(this);
				tvs[i][1].setTag("date" + i);// setting tag with index i
				tvs[i][1].setText(bkk.getDate().substring(0, bkk.getDate().length() - 5));
				tvs[i][1].setTextSize(12);
				tvs[i][1].setWidth(40);
				//tvs[i][1].setBackgroundColor(Color.BLUE);
				tvs[i][1].setHeight(120);
				tvs[i][1].setGravity(Gravity.CENTER_HORIZONTAL);
				// rowspan[i].addView(tvs[i][0]);
				tbrs[i].addView(tvs[i][1]);

				tvs[i][2] = new TextView(this);
				tvs[i][2].setTag("time" + i);// setting tag with index i
				tvs[i][2].setText(bkk.getTime());
				tvs[i][2].setTextSize(12);
				tvs[i][2].setWidth(160);
				tvs[i][2].setHeight(120);
				//tvs[i][2].setBackgroundColor(Color.GREEN);
				tvs[i][2].setGravity(Gravity.CENTER_HORIZONTAL);
				// rowspan[i].setPadding(0, 20, 0, 0);
				// rowspan[i].addView(tvs[i][1]);

				tbrs[i].addView(tvs[i][2]);

				// tbrs[i].addView(rowspan[i]);

				tvs[i][3] = new TextView(this);
				tvs[i][3].setTag("centre" + i);// setting tag with index i
				tvs[i][3].setText(bkk.getCentre());
				tvs[i][3].setTextSize(12);
				tvs[i][3].setWidth(190);
				tvs[i][3].setHeight(120);
				//tvs[i][3].setBackgroundColor(Color.BLUE);
				tvs[i][3].setGravity(Gravity.CENTER_HORIZONTAL);
				tvs[i][3].setPadding(0, 20, 0, 0);
				tbrs[i].addView(tvs[i][3]);

				tvs[i][4] = new TextView(this);
				tvs[i][4].setTag("court" + i);// setting tag with index i
				tvs[i][4].setText(bkk.getCourt());
				tvs[i][4].setTextSize(12);
				tvs[i][4].setWidth(55);
				tvs[i][4].setHeight(120);
				//tvs[i][4].setBackgroundColor(Color.GREEN);
				tvs[i][4].setGravity(Gravity.CENTER_HORIZONTAL);
				tvs[i][4].setPadding(0, 20, 0, 0);
				tbrs[i].addView(tvs[i][4]);

				tvs[i][5] = new TextView(this);
				tvs[i][5].setTag("activity" + i);// setting tag with index i
				String tmpActivity = bkk.getActivity().replaceAll("  ", "\n");
				tmpActivity = tmpActivity.replaceAll(" ", "\n");
				tvs[i][5].setText(tmpActivity);
				tvs[i][5].setTextSize(12);
				tvs[i][5].setWidth(130);
				tvs[i][5].setHeight(120);
				//tvs[i][5].setBackgroundColor(Color.YELLOW);
				tvs[i][5].setGravity(Gravity.CENTER_HORIZONTAL);
				tvs[i][5].setPadding(0, 20, 0, 0);
				tbrs[i].addView(tvs[i][5]);

				tvs[i][0] = new TextView(this);
				tvs[i][0].setTag("id" + i);// setting tag with index i
				tvs[i][0].setText(bkk.getId());
				tvs[i][0].setWidth(0);
				tvs[i][0].setHeight(0);
				tvs[i][0].setTextSize(0);
				
				//tvs[i][0].setGravity(Gravity.CENTER_HORIZONTAL);
				tvs[i][0].setVisibility(View.INVISIBLE);
				// rg.addView(rds[i]);
				tbrs[i].addView(tvs[i][0]);

				tbrs[i].setGravity(Gravity.CENTER_HORIZONTAL);

				tbl.addView(tbrs[i]);

			}
			tbrs[count] = new TableRow(this);
			tbrs[count].setBackgroundResource(R.color.color_deep_blue);
			TextView emptytvs;
			emptytvs = new TextView(this);

			emptytvs = new TextView(this);
			emptytvs.setTag("empty");// setting tag with index i
			emptytvs.setText("");
			emptytvs.setTextSize(10);
			emptytvs.setWidth(100);
			emptytvs.setHeight(30);
			emptytvs.setGravity(Gravity.CENTER);
			tbrs[count].addView(emptytvs);
			tbl.addView(tbrs[count]);
		} else {
			//DialogHelper.getOkAlertDialog(this, "Confirm Booking",
			//		"Booking can only be confirmed within 4 hours prior to the booked time slot.").show();
			YesAction yesAction = new YesAction() {
				public void fnDoYesAction() {
					finish();
				}
			};
			
			DialogHelper
			.getOkActionDialog(
					confirmbkActivity,
					"Confirm Booking",
					"No record has been found.",
					yesAction)
			.show();
			
		}

	}

	private void fnLoadConfirmBookData() {
		//remove old table rows for resume()
		removetbr();
		
		final ConfirmBookingActivity cbActivity = this;
		OnTaskCompleted completeAction = new OnTaskCompleted() {
			public void onTaskCompleted(Object resultList) {
				Log.d(TAG, "onTaskCompleted, bookings:" + resultList.toString());
				List<Booking> bookingList = (List<Booking>) resultList;
				cbActivity.fnSetConfirmBooking(bookingList);
			}

			public void onTaskFailed(String errMessage) {
				Log.e(TAG, errMessage);
				Toast.makeText(cbActivity,
						"Error loading booking...\n" + errMessage,
						Toast.LENGTH_LONG).show();
			}
		};
		ConfirmBookingPageTask cbTask = new ConfirmBookingPageTask(this, completeAction);
		cbTask.fnGetConfirmBookingList();
	}

	public void removetbr() {

		//remove table rows for reload
		TableLayout tbl = (TableLayout) findViewById(R.id.confirm_booking_table);		
		int count = tbl.getChildCount();
		for (int i = 1; i < count; i++) {
		    View child = tbl.getChildAt(i);
		    if (child instanceof TableRow) ((ViewGroup) child).removeAllViews();
		}
	}


	public void fnfailtoconfirm() {
		// show dialog if fail to cancel
		DialogHelper.getOkAlertDialog(this, "Fail to confirm booking.", "")
				.show();

	}
}
